
class SelectElement < Element

  Element.factory('select', self)
  Element.factory(:select, self)

  def options= o
    remove_children
    if o.first
      if o.first.is_a? Array
        o.each { |k, v| add_option k, v }
      else
        o.each { |v| add_option v }
      end
    end
    self
  end

  def add_option value, label = value
    self << el(:option, label, :value => value)
  end

  def value
    if option = selected_option
      option.get('value') || option.inner_html
    else
      nil
    end
  end

  def selected_option
    children.select { |ch| ch.get('selected') }.first
  end

  def option_for_value v
    v = v.to_s
    children.select { |ch|
      ch.value.to_s == v
    }.first || raise("No option for value #{v}")
  end

  def value= v
    "set value #{v} to #{self}"
    if o = selected_option
      o.set('selected', nil)
    end
    
    option_for_value(v).set('selected', 'selected')
  end



  class Test < FwTest
    def test_dump_nil_value
      s = SelectElement.new(:select, :name => 'number')
      s.options = (0..10).to_a
      post = s.dump
      eq post.length, 1, post.inspect
      eq post.first[1], nil, post.inspect
    end

    def test_dump_value
      s = SelectElement.new(:select, :name => 'number')
      s.options = (0..10).to_a
      s.value = 7
      post = s.dump
      eq post.length, 1, post.inspect
      eq post.first[1], 7
    end

    def test_recieve_only_when_there_is_a_key_in_data
      s = SelectElement.new(:select, :name => 'number')
      s.options = (0..10).to_a
      s.value = 8
      s.recieve({})
      eq s.value, 8
    end

    def test_recieve_works_with_string_values
      s = SelectElement.new(:select, :name => 'number')
      s.options = (0..10).to_a
      s.recieve({'number' => "6"})
      eq s.value, 6
    end

    def test_recieve_works_with_original_values
      s = SelectElement.new(:select, :name => 'number')
      s.options = (0..10).to_a
      s.recieve({'number' => 10})
      eq s.value, 10
    end
  end

end